package me.zhenqu.redis.utils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: yibing.tan
 * Date: 11-11-14
 * Time: 下午4:29
 * To change this template use File | Settings | File Templates.
 */
public class CollectionCoder extends CacheCoder<Collection<?>> {
    private CacheCoder innerCoder;

    public CollectionCoder(CacheCoder innerCoder) {
        this.innerCoder = innerCoder;
    }

    @Override
    public byte[] encode(Collection<?> o) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        writeBytes(bos, ByteUtil.parseInt(o.size(), 4));

        for (Object o1 : o) {
            byte[] encode = innerCoder.encode(o1);
            writeBytes(bos, ByteUtil.parseInt(encode.length, 4));
            writeBytes(bos, encode);
        }
        return bos.toByteArray();
    }

    @Override
    public Collection<?> decode(byte[] val, int offset, int size) {
        int len = ByteUtil.toInt(val, offset, 4);
        List<Object> arr = new ArrayList<Object>();
        offset += 4;
        for (int i = 0; i < len; i++) {
            int l = ByteUtil.toInt(val, offset, 4);
            offset += 4;
            arr.add(innerCoder.decode(val, offset, l));
            offset += l;
        }

        return arr;
    }
}
